package com.item.util;
/**
 * Created by bingone on 15/12/16.
 */

import com.alibaba.fastjson.JSONObject;
import com.base.http.HttpUtil;
import com.base.support.PropertySupport;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 短信http接口的java代码调用示例
 * 基于Apache HttpClient 4.3
 *
 * @author songchao
 * @since 2015-04-03
 */

public class YunPianUtil {

    //apikey
    private static String api_key = "d7158b43722650a6122bfad5238336f5";

    private static final String USERNAME = PropertySupport.getProperty("sms.account");
    private static String PASSWORD = PropertySupport.getProperty("sms.pwd");

    private static String SIGN = "【艺基因】";

    private static String SIGN2 = "【艺小锤】";

    //设置模板ID，如使用1号模板:【#company#】您的验证码是#code#
    private static  long tpl_id = 2305558;

    //模板id  --即将拍卖
    private static long tpl_id_2 = 2368036;

    //查账户信息的http地址
    private static String URI_GET_USER_INFO =
            "https://sms.yunpian.com/v2/user/get.json";

    //智能匹配模板发送接口的http地址
    private static String URI_SEND_SMS =
            "https://sms.yunpian.com/v2/sms/single_send.json";
    //群发
    private static String BATCH_SEND_SMS =
            "https://sms.yunpian.com/v2/sms/batch_send.json";

    //模板发送接口的http地址
    private static String URI_TPL_SEND_SMS =
            "https://sms.yunpian.com/v2/sms/tpl_single_send.json";

    //发送语音验证码接口的http地址
    private static String URI_SEND_VOICE =
            "https://voice.yunpian.com/v2/voice/send.json";

    //绑定主叫、被叫关系的接口http地址
    private static String URI_SEND_BIND =
            "https://call.yunpian.com/v2/call/bind.json";

    //解绑主叫、被叫关系的接口http地址
    private static String URI_SEND_UNBIND =
            "https://call.yunpian.com/v2/call/unbind.json";

    //编码格式。发送编码格式统一用UTF-8
    private static String ENCODING = "UTF-8";

    public static void main(String[] args) throws IOException,
            URISyntaxException {

        //修改为您要发送的手机号
//        String mobile = "18505195958";
//
//        String tpl_value = URLEncoder.encode("#code#", ENCODING) + "=" +
//                URLEncoder.encode("778899", ENCODING) + "&" + URLEncoder.encode("");
//        //模板发送的调用示例
//        System.out.println(tpl_value);
//        System.out.println(YunPianUtil.tplSendSms(tpl_value,
//                mobile));

        String result = batchSend("您的验证码是1234","18505195958,13401533776");
        System.out.println(result);
    }

    /**
     * 通过模板发送短信(不推荐)
     *
     * @param mobile    　接受的手机号
     * @return json格式字符串
     * @throws IOException
     */

    public static String tplSendSms(String value,
                                    String mobile) throws IOException {
        Map < String, String > params = new HashMap < String, String > ();
        params.put("apikey", api_key);
        params.put("tpl_id", String.valueOf(tpl_id));
        String tpl_value = URLEncoder.encode("#code#", ENCODING) + "=" +
                URLEncoder.encode(value, ENCODING) + "&" + URLEncoder.encode("");
        params.put("tpl_value", tpl_value);
        params.put("mobile", mobile);
        String result = post(URI_TPL_SEND_SMS, params);

        JSONObject respose = JSONObject.parseObject(result);
        if(!respose.get("code").equals(0)){
            return respose.get("msg").toString();
        }
        return "2";
    }

    public static String push(String phone,String content){
        Map<String,String> params = new HashMap<>();
        params.put("apikey",api_key);
        params.put("mobile",phone);
        params.put("text",SIGN2+content);
        String result = post(URI_SEND_SMS,params);
        JSONObject respose = JSONObject.parseObject(result);
        if(!respose.getInteger("code").equals(0)){
            return respose.get("msg").toString();
        }
        return "2";
    }

    public static String pushUser(String phone,String content){
        Map<String,String> params = new HashMap<>();
        params.put("apikey",api_key);
        params.put("mobile",phone);
        params.put("text",SIGN2+content);
        String result = post(URI_SEND_SMS,params);
        JSONObject respose = JSONObject.parseObject(result);
        if(!respose.getInteger("code").equals(0)){
            return respose.get("msg").toString();
        }
        return "2";
    }

    /**
     * 批量发送短信,相同内容多个号码,智能匹配短信模板
     *
     * @param text   需要使用已审核通过的模板或者默认模板
     * @param mobile 接收的手机号,多个手机号用英文逗号隔开
     * @return json格式字符串
     */
    public static String batchSend(String text, String mobile) {
        Map<String, String> params = new HashMap<String, String>();//请求参数集合
        params.put("apikey", api_key);
        params.put("text", text);
        params.put("mobile", mobile);
        return post(BATCH_SEND_SMS,  params);//请自行使用post方式请求,可使用Apache HttpClient
    }


    /**
     * 基于HttpClient 4.3的通用POST方法
     *
     * @param url       提交的URL
     * @param paramsMap 提交<参数，值>Map
     * @return 提交响应
     */

    public static String post(String url, Map < String, String > paramsMap) {
        CloseableHttpClient client = HttpClients.createDefault();
        String responseText = "";
        CloseableHttpResponse response = null;
        try {
            HttpPost method = new HttpPost(url);
            if (paramsMap != null) {
                List < NameValuePair > paramList = new ArrayList <
                        NameValuePair > ();
                for (Map.Entry < String, String > param: paramsMap.entrySet()) {
                    NameValuePair pair = new BasicNameValuePair(param.getKey(),
                            param.getValue());
                    paramList.add(pair);
                }
                method.setEntity(new UrlEncodedFormEntity(paramList,
                        ENCODING));
            }
            response = client.execute(method);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                responseText = EntityUtils.toString(entity, ENCODING);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return responseText;
    }
}